// pages/evaluate/evaluate.js
const app = getApp()
Page({
  data: {
    backendUrl: 'http://127.0.0.1:88/api/user/',
    coachId: null,
    evaluateList: []
  },

  onLoad(options) {
    this.setData({ coachId: options.id }, () => {
      this.loadEvaluations()
    })
  },

  // 加载评价数据
  loadEvaluations() {
    wx.showLoading({ title: '加载中...' })
    wx.request({
      url: `${this.data.backendUrl}get_evaluate.php`,
      method: 'GET',
      data: {
        action: 'list',
        coach_id: this.data.coachId
      },
      success: (res) => {
        if (res.data.status === 'success') {
          this.processData(res.data.list)
        }
      },
      complete: () => wx.hideLoading()
    })
  },

  // 处理数据格式
  processData(list) {
    const processed = list.map(item => ({
      ...item,
      rating: Number(item.rating) || 0, 
      user: {
        ...item.user,
        avatar: item.user.avatar || '/images/default-avatar.jpg'
      },
      create_time: this.formatTime(item.create_time)
    }))
    this.setData({ evaluateList: processed })
  },

  // 时间格式化
  formatTime(timeStr) {
    const isoTime = timeStr.replace(' ', 'T') + 'Z'
    const date = new Date(isoTime)

    return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
  },

  // 去评价点击
  handleSubmit() {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      wx.showToast({ title: '请先登录', icon: 'none' })
      setTimeout(() => {
        wx.navigateTo({ url: '/pages/login/login' })
      }, 1500)
      return
    }
    wx.navigateTo({
      url: `/pages/evaluate-submit/evaluate-submit?coach_id=${this.data.coachId}`
    })
  }
})